package com.miya.archetype.test.base;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;

import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 运行Sql脚本
 * sql脚本放在resources下的sql文件夹下
 */
public final class RunSqlScript {
    /**
     * <p>运行指定的sql脚本
     */
    public static void run(String filePath, String url, String username, String password) {

        Reader read = null;
        Connection conn = null;
        try {
            read = Resources.getResourceAsReader(filePath);

            // 建立连接
            conn = DriverManager.getConnection(url, username, password);

            // 创建ScriptRunner，用于执行SQL脚本
            ScriptRunner runner = new ScriptRunner(conn);
            runner.setErrorLogWriter(null);
            runner.setLogWriter(null);

            runner.setAutoCommit(true);//自动提交
            runner.setFullLineDelimiter(false);
            runner.setDelimiter(";");////每条命令间的分隔符
            runner.setSendFullScript(false);
            runner.setStopOnError(false);

            // 执行SQL脚本
            runner.runScript(read);
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            try{
                if(conn != null){
                    conn.close();
                }
                if(read != null){
                    read.close();
                }
            } catch (SQLException | IOException e){
                e.printStackTrace();
            }
        }
    }
}